package com.hxit.userserver.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hxit.userserver.entity.User;
import com.hxit.userserver.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hxit.common.vo.Result;

@RestController
@Api(tags = "用户接口")
@RequestMapping("/api/user/")
public class UserController {

    @Autowired
    private UserService userService;

    @Cacheable(value = "UserCache",key="'user.getUsers'")
    @ApiOperation(value = "新增用户")
    @PostMapping("save")
    public Result save(User user){
        return userService.save(user)?Result.ok():Result.fail("新增失败");
    }

    @ApiOperation(value = "修改用户")
    @PostMapping("update")
    public Result update(User user){
        return userService.updateById(user)?Result.ok():Result.fail("修改失败");
    }

    @ApiOperation(value="删除用户")
    @CacheEvict(value = "UserCache",key = "'user.getUsers'")
    @PostMapping("delete")
    public Result delete(User user) {
        return userService.removeById(user) ? Result.ok() : Result.fail("删除失败!");
    }

    @SentinelResource(fallback = "allError")
    @ApiOperation(value="查询用户")
    @GetMapping("all")
    public Result all(){
        System.out.println(userService.list());
        return Result.ok(userService.list());
    }

    public Result allError(){
        return Result.fail("亲，降级方法被执行");
    }

    @ApiOperation(value="件查询和分页")
    @GetMapping("page")
    public Result page(String name , @ApiParam("第几页") Integer page ,@ApiParam("一页的数据") Integer limit){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(name)){
            wrapper.like(User::getUsername,name);
        }
        return Result.ok(userService.page(new Page<>(page,limit),wrapper));
    }

    @ApiOperation(value = "查询电影评价")
    @GetMapping("userMovies")
    public Result findUserMovies(Integer movieid){
        return Result.ok(userService.findUserByMovieId(movieid));
    }

    @ApiOperation(value="登录")
    @GetMapping("login")
    public Result login(User user){
        return userService.login(user)?Result.ok() : Result.fail("登录失败!");
    }
}
